<template>
  <div class="page-box">
    <universal-table :columns="columns" :fetch-data="fetchTableData" permission-prefix="sys:nfc_campaign" :show-selection="true"
      :show-index="true" :show-operation="true" :operation-width="'180'" :bt1-name="''" :bt2-name="''" :export-file-name="'NFC营销活动'" :init-search-form="{}" @edit="handleEdit" @delete="handleDelete"
      @reset="reset" @status-change="handleStatusChange" @selection-change="handleSelectionChange" ref="table">
      
      <!-- 搜索区域扩展 -->
      <template #searchExtend>
        <el-form-item prop="status">
          <el-select v-model="searchForm.status" placeholder="活动状态" clearable>
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="merchant_id">
          <el-select v-model="searchForm.merchant_id" placeholder="选择商户" clearable filterable>
            <el-option v-for="item in merchantOptions" :key="item.id" :label="item.merchant_name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="nfc_permission_status">
          <el-select v-model="searchForm.nfc_permission_status" placeholder="NFC权限状态" clearable>
            <el-option v-for="item in nfcPermissionOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        
        <!-- 批量操作按钮区域 -->
        <el-form-item>
          <el-button type="success" icon="el-icon-check" @click="handleBatchEnable" :disabled="!hasSelection">
            批量启用
          </el-button>
          <el-button type="warning" icon="el-icon-close" @click="handleBatchDisable" :disabled="!hasSelection">
            批量禁用
          </el-button>
          <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete" :disabled="!hasSelection">
            批量删除
          </el-button>
          <el-button type="primary" @click="handleAdd">
            <i class="el-icon-plus"></i> 添加活动
          </el-button>
        </el-form-item>
      </template>

      <!-- 操作栏扩展 -->
      <template #operationExtend="{ row }">
        <el-tooltip content="编辑" placement="top">
          <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(row)" circle></el-button>
        </el-tooltip>
        <el-tooltip content="删除" placement="top">
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleCustomDelete(row)" circle></el-button>
        </el-tooltip>
        <el-tooltip content="生成链接" placement="top">
          <el-button size="mini" type="success" icon="el-icon-link" @click="handleGenerateLink(row)" circle></el-button>
        </el-tooltip>
        <el-tooltip content="复制链接" placement="top">
          <el-button size="mini" type="warning" icon="el-icon-document-copy" @click="handleCopyLink(row)" :disabled="!row.nfc_link" circle></el-button>
        </el-tooltip>
        <el-tooltip content="管理库存" placement="top">
          <el-button size="mini" type="info" icon="el-icon-box" @click="handleManageStock(row)" circle></el-button>
        </el-tooltip>
      </template>

      <!-- 商户名称列自定义显示 -->
      <template #merchant_name="{ row }">
        <span>
          <el-tooltip 
            :content="getMerchantStatusTooltip(row)" 
            placement="top" 
            effect="dark">
            <span class="merchant-status-icon">{{ getMerchantStatusIcon(row) }}</span>
          </el-tooltip>
          {{ row.merchant_name || '未知商户' }}
        </span>
      </template>
    </universal-table>

    <!-- 编辑/添加弹窗 -->
    <el-dialog :title="isEdit ? '编辑活动' : '添加活动'" :visible.sync="dialogVisible" width="600px">
      <el-form :model="formData" :rules="formRules" ref="form" label-width="120px">
        <el-form-item label="商户" prop="merchant_id">
          <el-select v-model="formData.merchant_id" placeholder="请选择商户" style="width: 100%;" filterable>
            <el-option v-for="item in merchantOptions" :key="item.id" :label="item.merchant_name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动名称" prop="campaign_name">
          <el-input v-model="formData.campaign_name" placeholder="请输入活动名称"></el-input>
        </el-form-item>
        <el-form-item label="活动状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="第三方任务链接" prop="third_party_task_url">
          <el-input v-model="formData.third_party_task_url" placeholder="请输入第三方任务链接"></el-input>
        </el-form-item>
        <el-form-item label="二维码路径" prop="qr_code_path">
          <el-input v-model="formData.qr_code_path" placeholder="请输入二维码路径"></el-input>
        </el-form-item>
        <el-form-item label="NFC链接" v-if="formData.nfc_link">
          <el-input v-model="formData.nfc_link" readonly>
            <el-button slot="append" @click="handleCopyLink(formData)">复制</el-button>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import UniversalTable from "@/components/TableComponent.vue";
import { getCampaignList, createCampaign, updateCampaign, deleteCampaign, setCampaignStatus, generateNfcLink, getMerchantList, batchSetCampaignStatus } from '@/api/nfc';

export default {
  name: 'NfcCampaignManage',
  components: {
    UniversalTable
  },
  data() {
    return {
      dialogVisible: false,
      isEdit: false,
      submitting: false,
      merchantOptions: [],
      columns: [
        {
          prop: "campaign_name",
          label: "活动名称",
          width: "200"
        },
        {
          prop: "merchant_name",
          label: "商户名称",
          width: "200",
          slot: "merchant_name"
        },
        {
          prop: "contacts",
          label: "联系人",
          width: "120"
        },
        {
          prop: "status",
          label: "活动状态",
          width: "120",
          formatter: (row) => {
            const nfcAuth = row.nfc_authorization || {};
            const nfcConfig = row.nfc_config || {};
            const isAuthorized = nfcAuth.is_authorized === 1;
            const isEnabled = nfcConfig.is_enabled === 1;
            
            // 优先级检查：授权状态 > 启用状态 > 活动状态
            if (!isAuthorized) {
              return '⚠️ 暂停（NFC权限已回收）';
            }
            
            if (!isEnabled) {
              return '⚠️ 暂停（NFC未启用）';
            }
            
            // 权限和启用都正常时，显示活动本身状态
            return row.status_text || (row.status === 1 ? '进行中' : '已暂停');
          }
        },
        {
          prop: "coupon_stats", 
          label: "优惠券统计",
          width: "140",
          formatter: (row) => {
            // 数据异常处理
            if (row.coupon_available === null || row.coupon_distributed === null) {
              return '❌ 数据加载失败';
            }
            if (row.coupon_available < 0 || row.coupon_distributed < 0) {
              return '⚠️ 数据异常';
            }
            
            // 正常显示
            const available = row.coupon_available || 0;
            const distributed = row.coupon_distributed || 0;
            
            // 可发券为0时添加警告标记
            if (available === 0) {
              return `⚠️ 可发: ${available} / 已发: ${distributed}`;
            }
            
            return `可发: ${available} / 已发: ${distributed}`;
          }
        },
        {
          prop: "nfc_link",
          label: "NFC链接",
          width: "300",
          formatter: (row) => row.nfc_link || '未生成'
        },
        {
          prop: "create_time_format",
          label: "创建时间",
          width: "180"
        }
      ],
      statusOptions: [
        { value: 1, label: '启用' },
        { value: 0, label: '禁用' }
      ],
      nfcPermissionOptions: [
        { value: 'authorized', label: '🟢 有权限' },
        { value: 'revoked', label: '🔴 权限已回收' }
      ],
      searchForm: {},
      formData: {
        id: null,
        merchant_id: null,
        campaign_name: '',
        status: 1,
        third_party_task_url: '',
        qr_code_path: '',
        nfc_link: ''
      },
      formRules: {
        merchant_id: [
          { required: true, message: '请选择商户', trigger: 'change' }
        ],
        campaign_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择活动状态', trigger: 'change' }
        ]
      },
      
      // 批量操作相关
      selectedRows: [],
      hasSelection: false
    };
  },
  async mounted() {
    await this.loadMerchantList();
  },
  methods: {
    // 获取表格数据
    async fetchTableData(params = {}) {
      const postData = Object.assign({}, params, this.searchForm);
      try {
        const result = await getCampaignList(postData);
        console.log('API返回数据:', result);
        console.log('处理后数据:', {
          list: result.data.list,
          total: result.data.total
        });
        return {
          list: result.data.list,
          total: result.data.total
        };
      } catch (e) {
        console.error('API调用错误:', e);
        this.$message.error(e.message);
        throw e;
      }
    },

    // 加载商户列表
    async loadMerchantList() {
      try {
        const result = await getMerchantList();
        if (result.code === 0) {
          this.merchantOptions = result.data;
        }
      } catch (e) {
        this.$message.error('加载商户列表失败');
      }
    },

    // 重置搜索
    reset() {
      this.searchForm = {};
    },

    // 添加活动
    handleAdd() {
      this.isEdit = false;
      this.formData = {
        id: null,
        merchant_id: null,
        campaign_name: '',
        status: 1,
        third_party_task_url: '',
        qr_code_path: '',
        nfc_link: ''
      };
      this.dialogVisible = true;
    },

    // 编辑活动
    handleEdit(row) {
      this.isEdit = true;
      this.formData = { ...row };
      this.dialogVisible = true;
    },

    // 删除活动 (TableComponent回调)
    async handleDelete(row) {
      try {
        const result = await deleteCampaign(row.id);
        if (result.code === 0) {
          this.$message.success('删除成功');
          this.$refs.table.refresh();
        } else {
          this.$message.error(result.message || '删除失败');
        }
      } catch (e) {
        this.$message.error(e.message);
      }
    },

    // 自定义删除活动 (带确认对话框)
    async handleCustomDelete(row) {
      this.$confirm('确认要删除这个活动吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const result = await deleteCampaign(row.id);
          if (result.code === 0) {
            this.$message.success('删除成功');
            this.$refs.table.refresh();
          } else {
            this.$message.error(result.message || '删除失败');
          }
        } catch (e) {
          this.$message.error(e.message);
        }
      });
    },

    // 状态变更
    async handleStatusChange(row) {
      try {
        const result = await setCampaignStatus(row.id, row.status);
        if (result.code === 0) {
          this.$message.success('状态更新成功');
        } else {
          this.$message.error(result.message || '状态更新失败');
          // 恢复原状态
          row.status = row.status === 1 ? 0 : 1;
        }
      } catch (e) {
        this.$message.error(e.message);
        // 恢复原状态
        row.status = row.status === 1 ? 0 : 1;
      }
    },

    // 生成NFC链接
    async handleGenerateLink(row) {
      try {
        const result = await generateNfcLink(row.id);
        if (result.code === 0) {
          this.$message.success('NFC链接生成成功');
          row.nfc_link = result.data.nfc_link;
          this.$refs.table.refresh();
        } else {
          this.$message.error(result.message || '生成链接失败');
        }
      } catch (e) {
        this.$message.error(e.message);
      }
    },

    // 复制链接
    handleCopyLink(row) {
      if (!row.nfc_link) {
        this.$message.warning('该活动还没有生成NFC链接');
        return;
      }
      
      // 使用 Clipboard API 复制文本
      if (navigator.clipboard) {
        navigator.clipboard.writeText(row.nfc_link).then(() => {
          this.$message.success('链接已复制到剪贴板');
        }).catch(() => {
          this.fallbackCopyTextToClipboard(row.nfc_link);
        });
      } else {
        this.fallbackCopyTextToClipboard(row.nfc_link);
      }
    },

    // 备用复制方法
    fallbackCopyTextToClipboard(text) {
      const textArea = document.createElement("textarea");
      textArea.value = text;
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      try {
        document.execCommand('copy');
        this.$message.success('链接已复制到剪贴板');
      } catch (err) {
        this.$message.error('复制失败，请手动复制');
      }
      document.body.removeChild(textArea);
    },

    // 提交表单
    async handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.submitting = true;
          try {
            const result = this.isEdit 
              ? await updateCampaign(this.formData)
              : await createCampaign(this.formData);
            
            if (result.code === 0) {
              this.$message.success(this.isEdit ? '更新成功' : '添加成功');
              this.dialogVisible = false;
              this.$refs.table.refresh();
            } else {
              this.$message.error(result.message || '操作失败');
            }
          } catch (e) {
            this.$message.error(e.message);
          } finally {
            this.submitting = false;
          }
        }
      });
    },

    // 处理选择变化
    handleSelectionChange(selection) {
      this.selectedRows = selection;
      this.hasSelection = selection.length > 0;
    },

    // 批量启用
    async handleBatchEnable() {
      if (!this.hasSelection) {
        this.$message.warning('请选择要启用的活动');
        return;
      }

      this.$confirm(`确认要启用选中的 ${this.selectedRows.length} 个活动吗？`, '批量启用', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const ids = this.selectedRows.map(row => row.id).join(',');
          await batchSetCampaignStatus(ids, 1);
          this.$message.success('批量启用成功');
          this.$refs.table.refresh();
          this.selectedRows = [];
          this.hasSelection = false;
        } catch (error) {
          this.$message.error('批量启用失败：' + error.message);
        }
      });
    },

    // 批量禁用
    async handleBatchDisable() {
      if (!this.hasSelection) {
        this.$message.warning('请选择要禁用的活动');
        return;
      }

      this.$confirm(`确认要禁用选中的 ${this.selectedRows.length} 个活动吗？`, '批量禁用', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const ids = this.selectedRows.map(row => row.id).join(',');
          await batchSetCampaignStatus(ids, 0);
          this.$message.success('批量禁用成功');
          this.$refs.table.refresh();
          this.selectedRows = [];
          this.hasSelection = false;
        } catch (error) {
          this.$message.error('批量禁用失败：' + error.message);
        }
      });
    },

    // 批量删除
    async handleBatchDelete() {
      if (!this.hasSelection) {
        this.$message.warning('请选择要删除的活动');
        return;
      }

      this.$confirm(`确认要删除选中的 ${this.selectedRows.length} 个活动吗？删除后无法恢复！`, '批量删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const promises = this.selectedRows.map(row => 
            deleteCampaign(row.id)
          );
          
          await Promise.all(promises);
          this.$message.success('批量删除成功');
          this.$refs.table.refresh();
          this.selectedRows = [];
          this.hasSelection = false;
        } catch (error) {
          this.$message.error('批量删除失败：' + error.message);
        }
      });
    },

    // 管理库存
    handleManageStock() {
      // 跳转到优惠券模板管理页面
      this.$router.push('/nfc/templates');
    },

    // 获取商户状态图标
    getMerchantStatusIcon(row) {
      const nfcAuth = row.nfc_authorization || {};
      const nfcConfig = row.nfc_config || {};
      const isAuthorized = nfcAuth.is_authorized === 1;
      const isEnabled = nfcConfig.is_enabled === 1;
      
      if (!isAuthorized) {
        return '🔴'; // 权限已回收
      } else if (!isEnabled) {
        return '🟡'; // 功能未启用
      } else {
        return '🟢'; // 正常授权
      }
    },

    // 获取商户状态提示文本
    getMerchantStatusTooltip(row) {
      const nfcAuth = row.nfc_authorization || {};
      const nfcConfig = row.nfc_config || {};
      const isAuthorized = nfcAuth.is_authorized === 1;
      const isEnabled = nfcConfig.is_enabled === 1;
      
      if (!isAuthorized) {
        return '🔴 NFC权限已回收 - 该商户的NFC功能使用权限已被回收';
      } else if (!isEnabled) {
        return '🟡 NFC功能未启用 - 该商户的NFC裂变功能未启用';
      } else {
        return '🟢 权限正常 - 该商户拥有完整的NFC功能权限';
      }
    }
  }
};
</script>

<style scoped>
.page-box {
  padding: 20px;
}

/* 操作按钮间距 */
.el-tooltip + .el-tooltip {
  margin-left: 4px;
}

/* 确保圆形按钮尺寸一致 */
.el-button.is-circle {
  width: 28px;
  height: 28px;
  padding: 0;
}

/* 商户状态图标样式 */
.merchant-status-icon {
  font-size: 14px;
  margin-right: 6px;
  cursor: help;
  display: inline-block;
}
</style>